import React, { useState } from "react";
import { CRow, CCol, CFormSelect, CForm, CFormLabel, CFormInput, CButton } from '@coreui/react';
import { useSelector } from 'react-redux';


const DoctorAbsent = () => {
    const [reasons, setReasons] = useState(['Больничный', 'Отпуск за свой счет', 'Отгул']);
    const [startDate, setStartDate] = useState('2024-06-22');
    const [days, setDays] = useState(1);
    const fullName = useSelector((state) => state.fullname);
    const token = useSelector((state) => state.token);

    const handleDateChange = (e) => {
        setStartDate(e.target.value);
    };

    const handleDaysChange = (e) => {
        setDays(e.target.value);
    };

    const sendAbsenceRequest = async () => {
        const reason = reasons[0];
        const startAbsent = startDate;
        const quantityDays = days;
    
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/users/absent/${fullName}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    reason: reason,
                    start_absent: startAbsent,
                    quantity_days: quantityDays,
                }),
            });
    
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
    
            const data = await response.json();
            console.log(data);
            alert('Ваша заявка на отсутствие учтена.')
        } catch (error) {
            console.error('There has been a problem with your fetch operation:', error);
        }
    };

    
    return (
        <>
            <h1>Буду отсутствовать</h1>
            <br />
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Причина отсутствия</CFormLabel>
                </CCol>
                <CCol xs={3}>
                    <CFormSelect 
                        aria-label="Причина отсутствия"
                        value={reasons[0]}
                        onChange={(e) => setReasons([e.target.value])}
                    >
                        {reasons.map((reason, index) => (
                            <option key={index} value={reason}>{reason}</option>
                        ))}
                    </CFormSelect>
                </CCol>
            </CRow>
            <br />
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Дата начала отсутствия</CFormLabel>
                </CCol>
                <CCol xs={3}>
                    <CFormInput
                        type="text"
                        placeholder="Дата начала отсутствия: 2024-06-22"
                        aria-label="sm input example"
                        value={startDate}
                        onChange={handleDateChange}
                    />
                </CCol>
            </CRow>
            <br />
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Количество дней отсутствия</CFormLabel>
                </CCol>
                <CCol xs={3}>
                    <CFormInput
                        type="text"
                        placeholder="Количество дней отсутствия"
                        aria-label="sm input example"
                        value={days}
                        onChange={handleDaysChange}
                    />
                </CCol>
            </CRow>
            <br />
            <CRow>
                <CCol xs={3}>
                <CButton 
                    color="light" 
                    variant="outline" 
                    onClick={sendAbsenceRequest}
                >
                    Отправить на согласование
                </CButton>

                </CCol>
            </CRow>
        </>
    );
};

export default DoctorAbsent;
